package tech.blueglacier.email;

import org.apache.commons.lang.StringUtils;
import org.apache.james.mime4j.codec.DecodeMonitor;
import org.apache.james.mime4j.dom.FieldParser;
import org.apache.james.mime4j.dom.field.UnstructuredField;
import org.apache.james.mime4j.field.AbstractField;
import org.apache.james.mime4j.stream.Field;
import tech.blueglacier.codec.EnhancedDecoderUtil;

/**
 * Simple unstructured field such as <code>Subject</code>.
 *
 * @author zhangxinchen
 * @since 2020/7/28
 */
public class SubjectFieldImpl extends AbstractField implements UnstructuredField {

    private boolean parsed;
    private String value;

    public SubjectFieldImpl(Field rawField, DecodeMonitor monitor) {
        super(rawField, monitor);
        this.parsed = false;
    }

    /**
     * @see org.apache.james.mime4j.dom.field.UnstructuredField#getValue()
     */
    public String getValue() {
        if (!parsed)
            parse();

        return value;
    }

    private void parse() {
        String body = getBody();
        if (StringUtils.isEmpty(body)) {
            value = "";
        } else {
            try {
                value = EnhancedDecoderUtil.concatAndDecodeWords(body);
            } catch (Exception e) {
                value = body;
            }
        }

        parsed = true;
    }

    public static final FieldParser<UnstructuredField> PARSER = SubjectFieldImpl::new;
}

